package com.crawler.harbour.task;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import com.crawler.harbour.common.DockCode;
import com.crawler.harbour.entity.XictShipMent;
import com.crawler.harbour.model.Notice;
import com.crawler.harbour.model.ShipmentNew;
import com.crawler.harbour.service.INoticeService;
import com.crawler.harbour.service.IShipmentNewService;
import com.crawler.harbour.utils.RuoKuai;
import com.crawler.harbour.utils.StorageDay;
import com.crawler.harbour.utils.UrlUtil;
import com.crawler.utils.BeanUtils;
import com.crawler.utils.RedisManager;
import com.crawler.utils.StringUtils;

/**
 * 厦门国际货柜船期查询
 *
 * @author wbsheng
 * @create 2018-04-11 14:45
 **/
@Service
@Lazy(false)
public class XICTTask extends StorageDay{

    private static final Logger LOGGER = LoggerFactory.getLogger(XICTTask.class);

    @Autowired
    IShipmentNewService shipmentNewService;

    @Autowired
    private INoticeService noticeService;

    /**
     * 每2小时执行
     * 厦门国际货柜船期查询
     */
    @Scheduled(cron = "0 0 0/2 * * ?")
    public void xict() {
    	if(!RedisManager.lock("ship:xict", 0)) {
    		return;
    	}
        //未离港
        Document document = getDocument(UrlUtil.XICTNOLEAVE);
        Elements jishuTrs = document.getElementsByClass("table_jishu");
        List<XictShipMent> resultList = new ArrayList<>();
        List<ShipmentNew> shipmentNewList = new ArrayList<>();
        handleDataTwo(jishuTrs, resultList);
        Elements oushuTrs = document.getElementsByClass("table_oushu");
        handleDataTwo(oushuTrs, resultList);
        LOGGER.info("未离港数据：" + resultList.size());
        //离港
        Document doc = getDocument(UrlUtil.XICTLEAVE);
        jishuTrs = doc.getElementsByClass("table_jishu");
        handleDataOne(jishuTrs, resultList);
        oushuTrs = doc.getElementsByClass("table_oushu");
        //获取到的数据封装到实体类并存放在resultList中
        handleDataOne(oushuTrs, resultList);
        LOGGER.info("未离港+离港数据：" + resultList.size());
        //判断数据是否为变化或者新增
        Date date = new Date();
        List<String> IdList =new ArrayList<>();
        for (XictShipMent shipMent :resultList) {
        	ShipmentNew shipmentNew = new ShipmentNew();
            String hashStr = RuoKuai.MD5(DockCode._HC+shipMent.getShipEnName()+shipMent.getVoyage());
            shipMent.setId(hashStr);
            shipmentNew.setId(hashStr);
            ShipmentNew temp = shipmentNewService.selectById(hashStr);
            Notice notice = new Notice();
            notice.setPortNo(DockCode._HC);
            shipmentNew.setWharfName("厦门国际码头");
            notice.setShipName(shipMent.getShipEnName());
            notice.setShipCnName(shipMent.getShipChName());
            notice.setCkShipTimer(shipMent.getVoyage());
            notice.setCkSailingDate(convertTime(shipMent.getLeaveTime()));
            notice.setIntoDate(convertTime(shipMent.getStoragePeriodTime()));
            notice.setOffDate(convertTime(shipMent.getWharfCutOff()));
            notice.setCutOffDate(convertTime(shipMent.getCustomsClearanceTime()));
            notice.setStatus(0);
            if(StringUtils.isNullOrEmpty(notice.getShipName())) {
            	notice.setShipName(notice.getShipCnName());
            }
            notice.setCreateTime(date);
            shipmentNew.setShipTimer(shipMent.getVoyage());
            shipmentNew.setBerthDate(convertTime(shipMent.getArrivalTime()));
            shipmentNew.setXzCutDate(convertTime(shipMent.getFumigationBoxTime()));
            shipmentNew.setSvcName(shipMent.getRouteName());
            shipmentNew.setOffLadingDate(shipMent.getWharfInterceptingTime());
            BeanUtils.copyProperties(notice,shipmentNew , "id","status","type","shipTimer","sailingDate");
            shipmentNew.setSailingDate(notice.getCkSailingDate());//这边得船期只有出口船期，航次也只有出口航次，所以保存进去得只有一条出口得数据
            boolean isOk = true;
	        if(temp!=null&&IdList.contains(temp.getId())) {
	        	isOk = false;
	        }
		      if(isOk) {	
		                 if(temp !=null&&!temp.getSailingDate().equals(shipmentNew.getSailingDate())){
		                	if(toString(temp.getSailingDate()).equals("")) {
		                		 notice.setType(0); 
		                	}else {
		                		 notice.setType(1);
		                    }
		                    notice.setId(null);
		                    notice.setOrigValue(temp.getSailingDate());
		                    noticeService.insert(notice);
		                }
		                 if(temp !=null&&!temp.getOffDate().equals(shipmentNew.getOffDate())){
		                     notice.setType(2);
		                     notice.setId(null);
		                     notice.setOrigValue(temp.getOffDate());
		                     noticeService.insert(notice);
		                 }
		                 if(temp !=null&&!temp.getIntoDate().equals(shipmentNew.getIntoDate())){
		                     notice.setType(3);
		                     notice.setId(null);
		                     notice.setOrigValue(temp.getIntoDate());
		                     noticeService.insert(notice);
		                 }
		                 if(temp!=null) {
		                	 IdList.add(temp.getId());
		                 }
		       }
            shipmentNewList.add(shipmentNew);
        }
        //更新或者插入数据
        shipmentNewService.insertOrUpdateAllColumnBatch(shipmentNewList, resultList.size());
        LOGGER.info("厦门国际货柜船期数据插入完毕！");
    }

    /**
     * 离港数据处理
     *
     * @param jishuTrs
     * @param resultList
     */
    private void handleDataOne(Elements jishuTrs, List<XictShipMent> resultList) {
        Date date = new Date();
        //获取tr标签
        for (Element tr : jishuTrs) {
             //获取td标签
            Elements tds = tr.getElementsByTag("td");
            XictShipMent shipMent = new XictShipMent(
                    tds.get(5).text(),
                    tds.get(6).text(),
                    tds.get(1).text(),
                    tds.get(2).text(),
                    tds.get(4).text(),
                    date,
                    tds.get(3).text()
            );
            //航线+航次+船名
            shipMent.setId(RuoKuai.MD5(shipMent.getVoyage() + shipMent.getShipEnName()));
            resultList.add(shipMent);
        }
    }

    /**
     * 未离港数据处理
     *
     * @param jishuTrs
     * @param resultList
     */
    private void handleDataTwo(Elements jishuTrs, List<XictShipMent> resultList) {
        Date date = new Date();
        for (Element tr : jishuTrs) {
            Elements tds = tr.getElementsByTag("td");
            XictShipMent shipMent = new XictShipMent(
                    tds.get(8).text(),
                    tds.get(10).text(),
                    tds.get(6).text(),
                    tds.get(1).text(),
                    tds.get(9).text(),
                    tds.get(2).text(),
                    tds.get(4).text(),
                    tds.get(7).text(),
                    tds.get(5).text(),
                    date,
                    tds.get(3).text()
            );
            //航线+航次+船名
            shipMent.setId(RuoKuai.MD5(shipMent.getVoyage() + shipMent.getShipEnName()));
            resultList.add(shipMent);
        }
    }

    /**
     * 获取网页
     *
     * @return
     * @throws Exception
     */
    public Document getDocument(String url) {
        try {
            return Jsoup.connect(url).get();
        } catch (IOException e) {
            return null;
        }
    }
    private String toString(Object data) {
    	if(data==null) {
    		return "";
    	}
    	return data.toString();
    	
    }
    private String convertTime(String date) {
    	if(StringUtils.isNullOrEmpty(date)) {
    		return "";
    	}
    	return date.substring(0, date.indexOf("("));
    	
    }
}
